import React, { useRef, useState } from 'react';
import _ from 'lodash';
import CommonTable from '@/components/CommonTable';
import DebounceWrapper from '@/components/DebounceWrapper';
import { Button, message, Popconfirm, Tooltip, Dropdown, Menu } from 'antd';
import {
  DeleteOutlined,
  EditOutlined,
  InfoCircleOutlined,
  PlusOutlined,
  SafetyCertificateOutlined,
  MoreOutlined,
  ApiOutlined,
} from '@ant-design/icons';
import RoleDialog from './components/roleDialog';
import AuthDrawer from './components/authDrawer';
import RoleDepartmentRelationDrawer from './components/roleDepartmentReationDrawer';
import { fetchRoleData, deleteRoleById, batchDeleteRoleByIds } from '@/services/system/role';

const DebounceButton = DebounceWrapper(Button);

export default () => {
  const tableRef = useRef(null);
  const [deleteLoading, setDeleteLoading] = useState(false);
  const [deleteLoadingIds, setDeleteLoadingIds] = useState([]);
  const [roleModalVisible, setRoleModalVisible] = useState(false);
  const [roleModalOptions, setRoleModalOptions] = useState({});
  const [roleAuthDrawerVisible, setRoleAuthDrawerVisible] = useState(false);
  const [roleAuthDrawerWithRoleId, setRoleAuthDrawerWithRoleId] = useState({});
  const [roleDepartmentRelationDrawerWithRoleId, setRoleDepartmentRelationDrawerWithRoleId] =
    useState('');

  // 切换loading
  const toggleDeleteLoading = (id, status) => {
    setDeleteLoadingIds((list) => {
      const nextList = [...list];
      if (status) {
        nextList.push(id);
      } else {
        const index = _.indexOf(nextList, id);
        if (index > -1) {
          nextList.splice(index, 1);
        }
      }
      return nextList;
    });
  };

  return (
    <>
      <CommonTable
        ref={tableRef}
        rowKey={'id'}
        indexRender
        rowSelection={{
          getCheckboxProps: (data) => ({ disabled: data.roleType !== 'custom_role' }),
        }}
        header={{
          headerTitle: '角色列表',
          headerToolsRender: true,
          headerButtonList: [
            {
              key: 'add',
              type: 'primary',
              label: '新增',
              icon: <PlusOutlined />,
            },
            {
              key: 'delete',
              danger: true,
              type: 'primary',
              label: '批量删除',
              loading: deleteLoading,
              confirmText: '确认批量删除所勾选的角色数据?',
              icon: <DeleteOutlined />,
            },
          ],
          headerButtonClick: async ({ key }) => {
            switch (key) {
              case 'add':
                setRoleModalVisible(true);
                break;
              case 'delete':
                const { refresh, getSelectedList } = tableRef.current;
                if (getSelectedList) {
                  const selectedList = getSelectedList();
                  if (selectedList && selectedList.length) {
                    setDeleteLoading(true);
                    try {
                      await batchDeleteRoleByIds({ ids: _.map(selectedList, 'id') });
                      refresh && refresh();
                      message.success('角色数据批量删除成功');
                    } catch (e) {
                      console.log('删除失败');
                    }
                    setDeleteLoading(false);
                  } else {
                    message.warning('请至少选择一项数据后再操作');
                  }
                }
                break;
            }
          },
        }}
        request={async (params) => {
          const { records, total } = await fetchRoleData(params);
          return { data: records, count: total };
        }}
        columns={[
          { title: '角色名称', dataIndex: 'roleName', columnControl: { typeList: 'search' } },
          { title: '角色编码', dataIndex: 'roleKey', columnControl: { typeList: 'search' } },
          {
            title: '角色类型',
            dataIndex: 'roleType',
            columnControl: { typeList: 'filter', filterDictType: 'role_type' },
          },
          {
            title: '角色状态',
            dataIndex: 'roleStatus',
            columnControl: { typeList: 'filter', filterDictType: 'role_status' },
          },
          {
            title: (
              <>
                操作
                <Tooltip placement="top" title={'系统预设角色暂不支持编辑和删除'}>
                  <InfoCircleOutlined className="tooltip-information-handle-icon" />
                </Tooltip>
              </>
            ),
            dataIndex: 'id',
            width: 200,
            render: (text, data) => {
              const isDefaultRole = data.roleType !== 'custom_role';
              const deleteLoading = _.includes(deleteLoadingIds, text);
              return (
                <>
                  <DebounceButton
                    type="link"
                    size="small"
                    icon={<EditOutlined />}
                    disabled={deleteLoading || isDefaultRole}
                    onClick={() => {
                      setRoleModalOptions(data);
                      setRoleModalVisible(true);
                    }}
                  >
                    编辑
                  </DebounceButton>
                  <Popconfirm
                    okText="确定"
                    cancelText="取消"
                    title={'确认删除该角色，删除后不可恢复'}
                    placement="topRight"
                    onConfirm={async () => {
                      toggleDeleteLoading(text, true);
                      try {
                        await deleteRoleById({ id: text });
                        const { refresh } = tableRef.current;
                        refresh && refresh();
                        message.success('角色删除成功');
                      } catch (e) {
                        console.log('删除失败');
                      }
                      toggleDeleteLoading(text, false);
                    }}
                  >
                    <DebounceButton
                      danger
                      type="link"
                      size="small"
                      icon={<DeleteOutlined />}
                      loading={deleteLoading}
                      disabled={isDefaultRole}
                    >
                      删除
                    </DebounceButton>
                  </Popconfirm>
                  <Dropdown
                    trigger={['click']}
                    disabled={deleteLoading}
                    overlay={
                      <Menu
                        items={[
                          { key: 'authority', icon: <SafetyCertificateOutlined />, label: '授权' },
                          {
                            key: 'departmentRelation',
                            icon: <ApiOutlined />,
                            label: '关联机构',
                          },
                        ]}
                        onClick={({ key }) => {
                          switch (key) {
                            case 'authority':
                              setRoleAuthDrawerVisible(true);
                              setRoleAuthDrawerWithRoleId(text);
                              break;
                            case 'departmentRelation':
                              setRoleDepartmentRelationDrawerWithRoleId(text);
                              break;
                          }
                        }}
                      />
                    }
                  >
                    <DebounceButton type="text" size="small">
                      更多
                      <MoreOutlined />
                    </DebounceButton>
                  </Dropdown>
                </>
              );
            },
          },
        ]}
      />
      <RoleDialog
        visible={roleModalVisible}
        options={roleModalOptions}
        closeModal={() => {
          setRoleModalOptions({});
          setRoleModalVisible(false);
        }}
        updateList={() => {
          const { refresh } = tableRef.current;
          refresh && refresh();
        }}
      />
      <AuthDrawer
        visible={roleAuthDrawerVisible}
        roleId={roleAuthDrawerWithRoleId}
        closeDrawer={() => {
          setRoleAuthDrawerWithRoleId('');
          setRoleAuthDrawerVisible(false);
        }}
      />
      <RoleDepartmentRelationDrawer
        visible={!!roleDepartmentRelationDrawerWithRoleId}
        roleId={roleDepartmentRelationDrawerWithRoleId}
        closeDrawer={() => {
          setRoleDepartmentRelationDrawerWithRoleId('');
        }}
      />
    </>
  );
};
